﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using QuickPasteToolWeb.Service;
using QuickPasteToolWeb.Model;
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.ComponentModel;
using System.Data.Common;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using QuickPasteToolWeb.Helper;

namespace QuickPasteToolWeb
{
    public partial class MainWindowViewModel : ObservableObject
    {
        private string? _contentDetail;

        public string ContentDetail
        {
            get => _contentDetail;
            set
            {
                SetProperty(ref _contentDetail, value);
                QueryFile();
            }
        }


        private IFileOperationService _operationService;
        private IWebClient _webClient;

        [ObservableProperty]
        private bool _isExistContent;

        [ObservableProperty]
        private ObservableCollection<ShowContent> _fileDatas;

        public MainWindowViewModel(IFileOperationService operationService, IWebClient webClient)
        {
            _operationService = operationService;
            _webClient = webClient;
        }

        [RelayCommand]
        public void AddNewFile()
        {
            _operationService.SaveFile(ContentDetail);
        }
        public void QueryFile()
        {
            FileDatas = new ObservableCollection<ShowContent>();
            if (string.IsNullOrEmpty(ContentDetail))
            {
                return;
            }
            var queryDatas = _operationService.QueryFile(ContentDetail);
            if (queryDatas.Any())
            {
                foreach (var item in queryDatas)
                {
                    FileDatas.Add(new ShowContent
                    {
                        Id = item.Id,
                        Description = item.ContentDetail,
                    });
                }
            }
            else if (SettingHelper.GetSetting().IsOpenWebSearch)
            {
                var queryWord = HttpUtility.UrlEncode(ContentDetail);
                var url = $"https://www.baidu.com/sugrec?json=1&prod=pc&wd={queryWord}";
                var webQueryResult = _webClient.GetSearchTip(url);
                var webQueryResultData = JsonConvert.DeserializeObject<JObject>(webQueryResult);
                var models = webQueryResultData["g"].Select(t => t["q"].ToString()).ToList();
                foreach (var item in models)
                {
                    FileDatas.Add(new ShowContent
                    {
                        Id = Guid.NewGuid(),
                        Description = item
                    });
                }
            }
            IsExistContent = FileDatas.Any();
        }
    }
}
